#include <stdlib.h>
#include <stdio.h>
#include "perseusHTTP.h"

/*
 * Read each part of the multipart/Form-data
 * A body of multipart/form-data contains :
 * Boundary
 * Header
 * Body
 *
 * The request is like that :
 * Boundary  <--i ---> isBoundary
 * CRLF		|_---> isCRLF
 * Headers1CRLF	| \
 * Headers2CRLF	| |
 * .....	| |-> readHeader
 * HeadersnCRLF	| |
 * CRLF		|_/
 * body		|
 * CRLF ________| ---> isCRLF
 * Boundary	  ---> isBoundary
 * --CRLF	  ---> isTheEndOfMultipart
 */

unsigned char
isCRLF(char * request, unsigned long requestLength)
{
	unsigned char ret=0;
	unsigned char CRLF[]="\r\n";
	unsigned char CRLFLength=2;
	unsigned long i=0;

	while (i<requestLength 
		&& request[i] != '\0' 
		&& i<CRLFLength
		&& request[i] == CRLF[i])
	{    
		i++;
	}
	if (i < CRLFLength)
	{
		ret = 0;
		goto end;
	}
	ret = 1;
end:
	return ret;
}

unsigned char
isTheEndOfMultipart(char * request, unsigned long requestLength)
{
	unsigned char ret = 0;
	unsigned char boundaryEnd[]="--\r\n";
	unsigned char boundaryEndLength=4;
	unsigned long i=0;
	
	while ( i<requestLength 
		&& request[i] != '\0'
		&& i<boundaryEndLength
		&& request[i] == boundaryEnd[i])
	{
		i++;
	}

	if (i < boundaryEndLength)
	{
		ret = 0;
		goto end;
	}
	ret = 1;
end:
	return ret;
}

/*
 * Read the header of multipart/form-data
 * The headers must begin the string
 * return the length of the headers
 * return 0 (error) 
 */

unsigned int
readHeader(char * request, unsigned long requestLength
	 )
{
	unsigned int headerLength = 0;
	unsigned char ret;
	char * cursor = request;
	unsigned long cursorLength = requestLength;
	unsigned long cursorLengthTmp = requestLength;

	if (requestLength == 0)
	{
		goto end;
	}
	/*Search the next CRLF*/
	/*Test if the length is 0
	 * then no data so end of the headers
	 * 	return
	 * else continue
	 */
	do{
		cursorLengthTmp = cursorLength;
		ret = gotoEndtheLine(&cursor,&cursorLength);
		if (ret == 0)
		{
			headerLength = 0;
			goto end;
		}
		
		if (cursorLength == (cursorLengthTmp-2))
		{
			/*
			 * Line is juste a CRLF 
			 * it's the end of the headers
			 */
			headerLength = requestLength - cursorLength;
			goto end;
		}

	}while( 0<cursorLength  );

end:
	return headerLength;
}

/* isBoundary :
 * 	return 1 if the request begin by the boundary
 * 	return 0 else 
 */
unsigned char
isBoundary(char *request, unsigned long requestLength,
	     const char * boundary, unsigned int boundaryLength)
{
	unsigned char ret = 0;
	unsigned long i = 0;
	
	while ( i< requestLength  
		&& request[i] != '\0'
		&& i<boundaryLength 
		&& request[i] == boundary[i])
	{    
	/*
     * fprintf(stderr,"i:%lu, RL: %lu, BL: %u, %c == %c \n",i,requestLength,boundaryLength,request[i], boundary[i]);
     */
            i++;
	}

	if (i < boundaryLength)
	{
		ret = 0;
		goto end;
	}
	ret = 1;
end:
	return ret;
}

